#include <rtdef.h>
#include <rtthread.h>
#include "RN8306.h"
#include "MQ.h"

rt_device_t RN8306dev;
rt_device_t RN8306dev_dma;

rt_sem_t spi_transfer_sem;
static void timerPN8306Out(void * parameter)
{
    rt_sem_release(spi_transfer_sem); 
}

static void RN8306_timer_init()
{
    rt_timer_t  timerRN8306;
    timerRN8306 = rt_timer_create( "timerRN8306", timerPN8306Out, RT_NULL, 20, RT_TIMER_FLAG_PERIODIC);
    rt_timer_start(timerRN8306);
}

void RN8306_thread_entry(void *parameter)
{
    spi_transfer_sem = rt_sem_create("8306_dma_sem", 0, RT_IPC_FLAG_FIFO);
    
    RN8306_timer_init();
    
    RN8306dev = rt_device_find(RN8306_SPI_DEVICE_NAME);
    if (RN8306dev)
    {
         rt_thread_delay(1000);
        /* 打开设备 */
        rt_device_open(RN8306dev, RT_DEVICE_OFLAG_RDWR);
    }
    
    RN8306dev_dma = rt_device_find(RN8306_DMA_SPI_DEVICE_NAME);
    if (RN8306dev_dma)
    {
        rt_device_open(RN8306dev_dma, RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_DMA_RX | RT_DEVICE_FLAG_DMA_TX | RT_DEVICE_FLAG_INT_TX);
        //波形初始化
        RN8306_Wave_Init();
        //打开dma接收

    }
    while(1)
    {
        rt_thread_delay(1000);
    }
}

void RN8306_DMA_thread_entry(void *parameter)
{
    struct rt_spi_message msg[1];
    while (1) 
    {
        rt_sem_take(spi_transfer_sem, RT_WAITING_FOREVER);
        if (RN8306dev_dma)
        {
            msg[0].send_buf   = RT_NULL;
            msg[0].recv_buf   = u8RxBuffer;
            msg[0].length     = 1152;
            msg[0].cs_take    = 0;
            msg[0].cs_release = 1;
            msg[0].next       = RT_NULL;
            rt_spi_transfer_message((struct rt_spi_device *)RN8306dev_dma, msg ); // 启动DMA接收
        }
    }
}
